//JS functions required for all pages

$(function(){
    $('button:not(.inactive)').live('mouseenter',
        //onMouseOver
        function(){
            $(this).css('background-position','center');
        });
       $('button:not(.inactive)').live('mouseleave',
        //onMouseOut
        function(){
            $(this).css('background-position','left');
        });
    //onMouseDown
    $('button:not(.inactive)').live('mousedown',        
        function(){
            $(this).css('background-position','right');
        });
    $('button:not(.inactive)').live('mouseup',
        function(){
            $(this).css('background-position','left');
        });
    $('input.disabled').live('focus', function(){
        $(this).blur();
    });
    global_search();
    help_dialog();
    print_pdf();
    redirectUser('redirect');
    $.stickyBar('#message_box');
    $('#global_search_input').focus();
    //$('#message_box').stickyfloat({ duration: 200 });
});


//JS functions for Global Search Component
function global_search(){
    var input = $('#global_search_input');
    var text = 'search...';
    input.val(text);
    input.focus(
    //onFocus
    function(){
        if($(this).val() == text){
            $(this).val('');
        }
    }).blur(
    //onBlur
    function(){
        var val = $(this).val();
        if(!val || val == text){
            $(this).val(text);
        }
    });
    $('#global_search_form').submit(function(event){
        input.addClass('sending');
    });
    $('#search_form').submit(function(event){
       $('#search_input').addClass('sending');
    });

}

function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    
    var ua = navigator.userAgent;
    var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null) {
        rv = parseFloat(RegExp.$1);
    }
    
    return rv;
}

function checkSupportedBrowser() {
    var supported = true;
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ver = getInternetExplorerVersion();
        
        if (ver > -1) {
            if (ver <= 8.0) {
                supported = false;
            }
        }
    }
    return supported;
}

function print_pdf(){
    $('#print_pdf').live('click', function(e) {
        if (checkSupportedBrowser()) {
            $('body').html2canvas();
        } else {
            alert("The browser you are using is not supported by this functionality. Please upgrade it to a more recent version.");
        }

        return false;
    });       
}
function help_dialog(){
    var $helpdialog = $('<div></div>')
    .html('<div id="help_dialog_content"></div>')
    .dialog({
        id: 'help_dialog',
        autoOpen: false,
        title: 'Help Documentation',
        resizable: false,
        draggable: false,
        modal: true,
        width: 800,
        height: 500
    });
    $('#help_doc').live('click', function(e){
        
        if($('#help_dialog_content').html() == ''){
           $('#help_dialog_content').html('<iframe src="' + base_url + 'documentation/" id="helpdoc_frame" frameborder="0"  vspace="0"  hspace="0"  marginwidth="0"  marginheight="0" width="775" height="428" scrolling="yes" />');
        }
        $helpdialog.dialog('open');
    });
    $('div.ui-widget-overlay').live('click', function(e){
        $helpdialog.dialog('close');
    });    
}
function redirectUser(id, base){
    var select = $('#' + id);
    select.change(function(){
        if(select.val()){
            var url = base? base_url : window.location;
            window.location = url + select.val();
        }
    });
}
function updateEnv(){
    var newEnv = $('#env').val();
    if(newEnv){
        $('#env_wrapper').html('Switching Environments... <img src="' + base_url + '/assets/images/ajax-loader.gif" />');
        $.post(base_url + 'admin/update_env/',
        {
            'env': newEnv
        },
        function(){
            window.location.replace(window.location);
        },
        'text');
    }
}
function sendFeedback(){
    var feedbackType = $('#feedback_select');
    var feedbackInput = $('#feedback_input');
    var feedbackSubmit = $('#feedback_submit');
	
    feedbackSubmit.click(function(){
        if(feedbackType.val() && feedbackInput.val()){
            $.post(base_url + 'feedback/ajax/', {
                'type':feedbackType.val(),
                'feedback': feedbackInput.val()
                },
            function(data){
                if(data.status == 'ok'){
                    $("div#panel").slideUp("slow");
                    $("#toggle a").toggle();
                    $('#message_box').html('<div class="ok message">Thank you for your feedback regarding the Operational Tools.</div>');
                    feedbackType.val('');
                    feedbackInput.val('');
                }else{
                    alert('There was an error sending the feedback, please try again');
                }
            }, 'json');
			
        }else{
            var error = '';
            if(!feedbackType.val()){
                error += "- Please pick the type feedback.\n";
            }
            if(!feedbackInput.val()){
                error += "- Please enter some feedback.\n";
            }
            alert(error);
        }
        return false;
    });
}
(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}

	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break;

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};


})(jQuery);



/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.Class = function(){};
  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
    // Populate our constructed prototype object
    Class.prototype = prototype;
    // Enforce the constructor to be what we expect
    Class.constructor = Class;
    // And make this class extendable
    Class.extend = arguments.callee;
    return Class;
  };
})();


var Optools = Class.extend({
    errors: [],
    confirmBox: null,
    init: function(url){
        this.msgBox = $('#message_box');
        this.loader = $('#dist_loader');
        this.baseUrl = url;        
    },
    showLoader: function(){
        this.loader.removeClass('invisible');
    },
    hideLoader: function(){
        this.loader.addClass('invisible');
    },
    buildMsg: function(type, message){
        var output = '<div class="' + type + ' message">' + message + '</div>';
        this.displayMsg(output);
    },
    displayMsg: function(html){
        this.msgBox.html(html);
        this.msgBox.slideDown();
    },
    hideMsg: function(){
        this.msgBox.html('');
    },
    hideConfirm: function(){
        this.confirmBox.addClass('invisible');
    },
    showConfirm: function(){
        this.confirmBox.removeClass('invisible');
    },
    eventValidation: function(){
        var len = $(this).data('len');
        var value = $(this).val();
        var str = value.split('');
        var validated = '';
        var num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        for (var i = 0; i < str.length; i++) {
            for (var n in num) {
                if (n == str[i]) {
                    validated += str[i];
                    break;
                }
            }
        }
        if (validated.length >= len) {
            $(this).val(validated.substring(0, len));
        }
        else {
            $(this).val(validated);
        }
    }
});

(function($) {
    $.fn.getHiddenDimensions = function(boolOuter) {
        var $item = this;
        var props = { position: 'absolute', visibility: 'hidden', display: 'block' };
        var dim = { 'w':0, 'h':0 };
        var $hiddenParents = $item.parents().andSelf().not(':visible');

        var oldProps = [];
        $hiddenParents.each(function() {
        var old = {};

        for ( var name in props ) {
            old[ name ] = this.style[ name ];
            this.style[ name ] = props[ name ];
        }

        oldProps.push(old);
        });

        dim.w = (boolOuter === true) ? $item.outerWidth(true) : $item.width();
        dim.h = (boolOuter === true) ? $item.outerHeight(true) : $item.height();

        $hiddenParents.each(function(i) {
        var old = oldProps[i];
        for ( var name in props ) {
            this.style[ name ] = old[ name ];
        }
        });

        return dim;
    }
}(jQuery));



var LoaderClass = Class.extend({
    counter: 0,
    visible: false,
    loader: 'dist_loader',
    init: function(loader){
        if (loader) {
            this.loader = loader;
        }
    },
    show: function(){
        this.counter++;
        if(!this.visible){
            this.display();
        }
    },
    hide: function(){
        this.counter--;
        if(this.counter == 0){
            this.remove();
        }
    },
    display: function(){
        $('#' + this.loader).removeClass('invisible');
        this.visible = true;
    },
    remove: function(){
        $('#' + this.loader).addClass('invisible');
        this.visible = false;
    }
});
var Loader = new LoaderClass();

var MessageClass = Class.extend({
    messageBox: 'message_box',
    messages: {},
    init: function(){

    },
    newMsg: function(type, message, id){
        var html = '<div class="' + type + ' message">' + message + '</div>';
        if(!id){
            id = this.messages.length + 1;
        }
        this.messages[id] = html;
        this.display(html);
    },
    display: function(html){
        $('#' + this.messageBox).html(html);
        $('#' + this.messageBox).slideDown();
    },
    remove: function(id){
        if(id){
            this.messages[id] = null;
            $('#' + this.messageBox).html('');
            for(id in this.messages){
                this.display(this.messages[id]);
            }
        }else{
            this.clear();
        }
    },
    clear: function(){
        $('#' + this.messageBox).html('');
    }
});

var Message = new MessageClass();

var AjaxRequest = Class.extend({
    options: {
        url:      '',
        data: '',
        dataType: 'json',
        type:     'POST',
        success:  function(){}
    },
    //retries: 0,
    init: function(options){
        this.options.dataType = 'json';
        this.options.type = 'POST';
        this.options = $.extend(this.options, options);
        this.options.url = base_url + this.options.url;
        this.request();
    },
    request: function(){
        var self = this;
        $.ajax({
          beforeSend: function(){
            Loader.show();
          },
          url: this.options.url,
          data: this.options.data,
          dataType: this.options.dataType,
          type: this.options.type,
          success: this.options.success,
          complete: function(){
            Loader.hide();
          },
          error: function( xhr, tStatus, err ) {
            Loader.hide();
            if( xhr.status === 401 || xhr.status === 403 || xhr.status === 500 || xhr.status === 404) {
                Message.newMsg('error', 'There was an error processing your request.<br />'
                                        + 'Please try again, or contact an administrator.<br />Code: '
                                        + xhr.status + ' Process: ' + self.options.url);
            } else if ( xhr.status === 504 && !retries++ ) {
                Message.newMsg('alert', 'The server was unresponsive to your request.<br />Resending...');
                self.request();
            }
          }
        });
    }
});
